package org.heydr.common.filter.impl;

import java.util.BitSet;

import org.heydr.annotation.FilterMapping;
import org.heydr.common.filter.Filter;

@FilterMapping(name="bloom")
public class BloomFilter implements Filter{

    private static final int DEFAULT_SIZE = 5000 << 10000;
    private static final int[] seeds = {3, 5, 7, 11, 13, 31, 37, 61};
    private static BitSet bits = new BitSet(DEFAULT_SIZE);
    
    public synchronized void add(String value){
        if(value != null){
        	for(int seed : seeds){
        		bits.set(hash(value,seed),true);
        	}
        }
    }
    
    public boolean contains(String value){
        if(value == null) 
        	return false;
        boolean ret = true;
        for(int seed : seeds){
        	ret = ret && bits.get(hash(value,seed));
        }
        return ret;
    }
    
    private static int hash(String value,int seed){
        int result = 0;
        int len = value.length();
    	for (int i = 0; i < len; i++) {
    		result = seed * result + value.charAt(i);
    	}
        return (DEFAULT_SIZE - 1) & result;
    }
}